<template>
  <div class="audio-container">
    <div class="main-content">
      <!-- 配置面板 -->
      <div class="selection-panel">
        <h2>音频生成配置</h2>
        
        <!-- 学习阶段选择 -->
        <div class="form-item">
          <label>学习阶段</label>
          <el-select v-model="formData.stage" placeholder="请选择学习阶段" @change="handleStageChange">
            <el-option
              v-for="item in stages"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>

        <!-- 学习科目选择 -->
        <div class="form-item">
          <label>学习科目</label>
          <el-select v-model="formData.subject" placeholder="请选择学习科目" @change="handleSubjectChange">
            <el-option
              v-for="item in subjects"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>

        <!-- 教学目标选择 -->
        <div class="form-item">
          <label>教学目标</label>
          <el-select v-model="formData.objective" placeholder="请选择教学目标" @change="handleObjectiveChange">
            <el-option
              v-for="item in objectives"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>

        <!-- 音频时长选择 -->
        <div class="form-item">
          <label>音频时长</label>
          <el-select v-model="formData.duration" placeholder="请选择音频时长">
            <el-option label="1-3分钟" value="short" />
            <el-option label="3-5分钟" value="medium" />
            <el-option label="5-10分钟" value="long" />
          </el-select>
        </div>

        <!-- 音频类型选择 -->
        <div class="form-item">
          <label>音频类型</label>
          <el-select v-model="formData.type" placeholder="请选择音频类型">
            <el-option label="讲解音频" value="explanation" />
            <el-option label="朗读音频" value="reading" />
            <el-option label="听力练习" value="listening" />
            <el-option label="对话音频" value="conversation" />
          </el-select>
        </div>
      </div>

      <!-- AI对话区域 -->
      <div class="ai-dialog">
        <h2>AI助手</h2>
        <div class="chat-container">
          <div class="chat-messages" ref="chatMessages">
            <div v-for="(message, index) in chatMessages" :key="index" 
                 :class="['message', message.type]">
              <div class="message-content">{{ message.content }}</div>
            </div>
          </div>
          <div class="chat-input">
            <el-input
              v-model="userInput"
              type="textarea"
              :rows="3"
              placeholder="请输入您的问题或要求..."
              @keyup.enter.ctrl="sendMessage"
            />
            <el-button type="primary" @click="sendMessage">发送</el-button>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-panel">
        <el-button type="primary" @click="generateAudio" :loading="generating">
          生成音频
        </el-button>
      </div>

      <!-- 生成的音频列表 -->
      <div v-if="audioList.length > 0" class="audio-list">
        <h2>生成的音频</h2>
        <div v-for="(audio, index) in audioList" :key="index" class="audio-item">
          <div class="audio-header">
            <span class="audio-title">{{ audio.title }}</span>
            <span class="audio-duration">{{ audio.duration }}</span>
          </div>
          <div class="audio-player">
            <audio controls :src="audio.url"></audio>
          </div>
          <div class="audio-actions">
            <el-button type="primary" link @click="downloadAudio(audio)">
              下载音频
            </el-button>
            <el-button type="primary" link @click="previewAudio(audio)">
              预览
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 历史记录预览面板 -->
    <div class="history-panel">
      <h3>历史记录</h3>
      <div class="history-list">
        <div v-for="(item, index) in historyList" 
             :key="index"
             :class="['history-item', { active: selectedHistory === index }]"
             @click="selectHistory(index)">
          <div class="history-title">{{ item.title }}</div>
          <div class="history-time">{{ item.time }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { fetchHistoryList } from '@/api/history'
import axios from 'axios'

// 表单数据
const formData = ref({
  stage: '',
  subject: '',
  objective: '',
  duration: '',
  type: ''
})

// 选项数据
const stages = ref([
  { value: 'primary', label: '小学' },
  { value: 'junior', label: '初中' },
  { value: 'senior', label: '高中' },
  { value: 'university', label: '大学' }
])

// 模拟科目数据
const subjectsMap = {
  primary: [
    { value: 'chinese', label: '语文' },
    { value: 'english', label: '英语' },
    { value: 'math', label: '数学' }
  ],
  junior: [
    { value: 'chinese', label: '语文' },
    { value: 'english', label: '英语' },
    { value: 'math', label: '数学' },
    { value: 'physics', label: '物理' },
    { value: 'chemistry', label: '化学' }
  ],
  senior: [
    { value: 'chinese', label: '语文' },
    { value: 'english', label: '英语' },
    { value: 'math', label: '数学' },
    { value: 'physics', label: '物理' },
    { value: 'chemistry', label: '化学' },
    { value: 'biology', label: '生物' }
  ],
  university: [
    { value: 'english', label: '大学英语' },
    { value: 'math', label: '高等数学' },
    { value: 'physics', label: '大学物理' }
  ]
}

// 模拟教学目标数据
const objectivesMap = {
  chinese: [
    { value: 'reading', label: '阅读理解' },
    { value: 'writing', label: '写作表达' },
    { value: 'listening', label: '听力训练' }
  ],
  english: [
    { value: 'vocabulary', label: '词汇学习' },
    { value: 'grammar', label: '语法掌握' },
    { value: 'speaking', label: '口语练习' },
    { value: 'listening', label: '听力训练' }
  ],
  math: [
    { value: 'concept', label: '概念理解' },
    { value: 'calculation', label: '计算能力' },
    { value: 'application', label: '应用能力' }
  ]
}

const subjects = ref([])
const objectives = ref([])

// 聊天相关
const chatMessages = ref([])
const userInput = ref('')
const chatMessagesRef = ref(null)

// 音频相关
const audioList = ref([])
const generating = ref(false)

// 历史记录相关
const historyList = ref([])
const selectedHistory = ref(null)

// 加载历史记录
const loadHistoryList = async () => {
  try {
    const response = await fetchHistoryList()
    historyList.value = response.data
  } catch (error) {
    ElMessage.error('加载历史记录失败')
  }
}

// 处理学习阶段变化
const handleStageChange = (value) => {
  formData.value.subject = ''
  formData.value.objective = ''
  subjects.value = subjectsMap[value] || []
  objectives.value = []
}

// 处理科目变化
const handleSubjectChange = (value) => {
  formData.value.objective = ''
  objectives.value = objectivesMap[value] || []
}

// 处理教学目标变化
const handleObjectiveChange = (value) => {
  // 可以在这里添加额外的逻辑
}

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim()) return
  
  // 添加用户消息
  chatMessages.value.push({
    type: 'user',
    content: userInput.value
  })
  
  // 清空输入
  const message = userInput.value
  userInput.value = ''
  
  try {
    // 调用AI接口
    const response = await axios.post('/api/chat', {
      message,
      context: {
        stage: formData.value.stage,
        subject: formData.value.subject,
        objective: formData.value.objective,
        duration: formData.value.duration,
        type: formData.value.type
      }
    })
    
    // 添加AI回复
    chatMessages.value.push({
      type: 'ai',
      content: response.data.reply
    })
    
    // 滚动到底部
    setTimeout(() => {
      if (chatMessagesRef.value) {
        chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight
      }
    }, 100)
  } catch (error) {
    ElMessage.error('发送消息失败')
  }
}

// 生成音频
const generateAudio = async () => {
  if (!formData.value.stage || !formData.value.subject || !formData.value.objective || 
      !formData.value.duration || !formData.value.type) {
    ElMessage.warning('请完善音频生成配置')
    return
  }
  
  generating.value = true
  try {
    const response = await axios.post('/api/audio/generate', {
      ...formData.value,
      chatHistory: chatMessages.value
    })
    
    // 添加新生成的音频
    audioList.value.unshift({
      title: response.data.title,
      duration: response.data.duration,
      url: response.data.url
    })
    
    ElMessage.success('音频生成成功')
  } catch (error) {
    ElMessage.error('音频生成失败')
  } finally {
    generating.value = false
  }
}

// 下载音频
const downloadAudio = (audio) => {
  // 实现下载逻辑
  ElMessage.success('开始下载音频')
}

// 预览音频
const previewAudio = (audio) => {
  // 实现预览逻辑
  ElMessage.success('开始预览音频')
}

// 选择历史记录
const selectHistory = (index) => {
  selectedHistory.value = index
  // 这里可以添加加载历史记录的逻辑
}

onMounted(() => {
  // 初始化加载
  if (formData.value.stage) {
    handleStageChange(formData.value.stage)
  }
  loadHistoryList()
})
</script>

<style scoped>
.audio-container {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  gap: 20px;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 0px;
}

.selection-panel {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-item {
  margin-bottom: 20px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.ai-dialog {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chat-container {
  height: 400px;
  display: flex;
  flex-direction: column;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 10px;
}

.message {
  margin-bottom: 10px;
  max-width: 80%;
}

.message.user {
  margin-left: auto;
}

.message.ai {
  margin-right: auto;
}

.message-content {
  padding: 10px;
  border-radius: 4px;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.message.user .message-content {
  background: #1a73e8;
  color: #fff;
}

.chat-input {
  display: flex;
  gap: 10px;
}

.chat-input .el-input {
  flex: 1;
}

.action-panel {
  text-align: center;
  margin: 20px 0;
}

.audio-list {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.audio-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.audio-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: #666;
}

.audio-title {
  color: #1a73e8;
  font-weight: 500;
}

.audio-duration {
  color: #909399;
}

.audio-player {
  margin: 10px 0;
}

.audio-player audio {
  width: 100%;
}

.audio-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.history-panel {
  width: 300px;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: fit-content;
}

.history-panel h3 {
  margin-bottom: 15px;
  color: #333;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.history-item {
  padding: 10px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.history-item:hover {
  background-color: #f5f7fa;
}

.history-item.active {
  background-color: #ecf5ff;
  color: #1a73e8;
}
</style>